﻿using System;
namespace QuickSilver.Help.String
{
    /// <summary>
    /// 字符串通用操作类
    /// </summary>
    public class StrUtility
    {
        /// <summary>
        /// 判读字符串是否为数字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsInteger(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return false;
            }
            else
            {
                char[] tmp=new char[str.Length];
                tmp = str.ToCharArray();
                for (int i = 0; i < tmp.Length; i++)
                {
                    //利用ASCII 码码值进行比较
                    if (tmp[i] < 48 && tmp[i] > 57)
                        return false;
                }
                return true;
            }
        }

        /// <summary>
        /// 判读字符串是否为数字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsNumber(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return false;
            }
            else
            {
                char[] tmp = new char[str.Length];
                tmp = str.ToCharArray();
                for (int i = 0; i < tmp.Length; i++)
                {
                    //利用ASCII 码码值进行比较
                    if (!char.IsNumber(tmp[i]))
                        return false;
                }
                return true;
            }
        }

        /// <summary>
        /// 将字符串转换为整数
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int ConvertToInt(string str)
        {
            int nResult = 0;
            int temp = 0;
            if (!string.IsNullOrEmpty(str))
            {
                if (QuickSilver.Help.String.StrUtility.IsInteger(str))
                {
                    for(int i=0;i<str.Length;i++)
                    {
                        //首个元素时nResult 为0
                        temp = nResult;
                        nResult=nResult*10+((int)str[i]-48); //0的ASCII码为48
                        if (temp == nResult)
                            continue;//???
                    }
                    if (temp != nResult)
                    {
                        throw new System.Exception("已经溢出！");
                    }
                }
            }
            return nResult;

        }
    }
}